package com.news.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.news.entity.User;
import com.news.service.UserService;


@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String password_chk=request.getParameter("password_chk");
		String role="1";//默认注册为普通用户
		String sex=request.getParameter("sex");
		String age=request.getParameter("age");
		String check = request.getParameter("check");
		User user=new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setRole(role);
		user.setSex(Integer.parseInt(sex));
		user.setAge(Integer.parseInt(age));
		response.setContentType("text/html; charset=UTF-8");
		if(!password.equals(password_chk)){
			System.out.println("两次密码输入不一致！");
			response.getWriter().print("<script> alert(\"两次密码输入不一致！\"); </script>");
			response.setHeader("refresh", "0.2;url=jsp/register.jsp");
			return;
		}
		
		if(check == null){
			System.out.println("只有同意《用户注册协议》才可以注册！");
			response.getWriter().print("<script> alert(\"只有同意《用户注册协议》才可以注册！\"); </script>");
			response.setHeader("refresh", "0.2;url=jsp/register.jsp");
			return;
		}
		
		UserService us =new UserService();
		boolean flag=us.addUser(user);
		
		if(flag){
			System.out.println("注册成功!");
			response.getWriter().print("<script> alert(\"注册成功!\"); </script>");
			response.setHeader("refresh", "0.2;url=jsp/login.jsp");
		}else{
			System.out.println("注册失败!");
			response.getWriter().print("<script> alert(\"注册失败!\"); </script>");
			response.setHeader("refresh", "0.2;url=jsp/register.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	

}
